package com.bosc.modeling.controller;

import com.bosc.modeling.common.BaseController;
import com.bosc.modeling.common.ResponseFactory;
import com.bosc.modeling.pojo.gen.EnrollEntity;
import com.bosc.modeling.pojo.gen.TeamEntity;
import com.bosc.modeling.pojo.gen.UserEntity;
import com.bosc.modeling.service.TeamService;
import com.bosc.modeling.service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author yuanyj
 * @version 1.0
 * @date 2019/11/25 10:50
 * @description
 */
@RestController
public class TeamController extends BaseController {
    @Autowired
    TeamService teamService;
    @Autowired
    UserService userService;
    @RequestMapping(value = "get_my_team", method = RequestMethod.POST)
    public Object getMyTeam(@RequestBody String body) throws JSONException {
        log.info("getMyTeam:"+body);
        try {
            JSONObject obj = new JSONObject(body);
            String competitionId = obj.getString("competition_id");
            String userId = obj.getString("user_id");
            List<EnrollEntity> enrolls = teamService.getEnrollByCompetitionId(competitionId);
            for (EnrollEntity enroll:enrolls) {
                List<TeamEntity> teams = teamService.getTeamByUserId(enroll.getTeamId(),userId);
                if (teams.size() > 0){
                    List<TeamEntity> teamEntities = teamService.getTeamByTeamId(teams.get(0).getTeamId());
                    List<UserEntity> users = new ArrayList<>();
                    for (TeamEntity team:teamEntities) {
                        users.addAll(userService.getUserById(team.getUserId()));
                    }
                    HashMap<String,Object> resp = new HashMap<>();
                    resp.put("teams",teamEntities);
                    resp.put("users",users);
                    log.info("getMyTeam:返回结果-" + resp.toString());
                    return ResponseFactory.successResponse(resp);
                }
            }
            log.info("getMyTeam:参数错误");
            return ResponseFactory.failureResponse("1","参数错误");
        }catch (JSONException e){
            e.printStackTrace();
            throw e;
        }

    }
}
